// 函数组件
import React, { useState, useEffect, useContext } from 'react';
import { ConfigProvider, Form, Input, Button, Table, Switch, Select, DatePicker, Modal } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import Compile from './child/Compile'; //编辑弹框
import zh_CN from 'antd/es/locale/zh_CN';
import { useNavigate } from 'react-router-dom';
import type { DatePickerProps } from 'antd';
import './Css/Promontion.less'
import '../../css/public.less'
import { ExclamationCircleFilled } from '@ant-design/icons';
import {getAllPromotion,delData,deTypeApi,changePromotionState, getGoods} from '../../../api/wj'
    //表格数据类型
    interface DataType {
        key ?: React.Key; //序号
        id :number;//id
        title : string; //促销标题name
        detial : string; //促销详情detail
        type : string; //使用行程address
        state : number //以未上架判断 isPut
        creat : string//添加时间 time
    }
function Promotionma() {
    const [count,setCount] = useState<number>()//用条数
    //排序的方式名
    const [sortName,setSortName] = useState<{value:string,label:string}[]>([{ value: '升序', label: '升序' },{ value: '降序', label: '降序' }])
    const { confirm } = Modal;
    //input 值
    const [title, setTitle] = useState<string>('')
    // 日期 值
    const [creat, setCreat] = useState<string>('')
    //select 值
    const [state, setState] = useState<{ state: number, choose: string }|null>()
    //所有的使用行程
    const [types,setTypes] = useState<{sportId:number,sportName:string}[]>([])
    const columns: ColumnsType<DataType> = [
        {
            title: '序号',
            dataIndex: 'id',
        },
        {
            title: '促销标题',
            dataIndex: 'title',
        },
        {
            title: '促销详情',
            dataIndex: 'detial',
        },
        {
            title: '使用行程',
            dataIndex: 'type',
        },
        {
            title: '是否上架',
            dataIndex: 'state',
            render: (_, v) =>
            (
                <Switch
                    defaultChecked={v.state == 1?true:false}
                    onChange={onChange}
                    onClick={() => { switchClick(v ) }} />
            )
        },
        {
            title: '添加时间',
            dataIndex: 'creat',
        },
        {
            title: '操作',
            dataIndex: 'address',
            width: 310,
            render: (_, v) => (
                <div className='operationList'>
                    <button className='shop-manage' onClick={() => { commodityBtn(v) }}>商品管理</button>
                    <button className='edit' onClick={() => { redactBtn(v) }}>编辑</button>
                    <button className='del' onClick={() => { showPromiseConfirm(v) }}>删除</button>
                </div>
            )
        },
    ];
    //删除函数
    const showPromiseConfirm = (v:any) => {
        confirm({
            title: '确认删除此信息',
            icon: <ExclamationCircleFilled />,
            content: 'When clicked the OK button, this dialog will be closed after 1 second',
            onOk() {
                return new Promise((resolve, reject) => {
                    setTimeout(Math.random() > 0.5 ? resolve : reject, 1000);
                    console.log(v);
                    delData({id:v.id}).then(res=>{
                        console.log('删除成功',res);
                        if(res.code=='200'){
                            getvalue()
                        }
                    }).catch(err=>console.log('失败',err))
                }).catch(() => console.log('Oops errors!'));
            },
            onCancel() { },
        });
    };
    //用户数据
    const [data,setData] = useState<DataType[]>([])

    const [switchList, setSwitchList] = useState<{ state: number, choose: string }[]>([{ state: 1, choose: '上架' }, { state: 2, choose: '未上架' }])
    //总筛选需要的内容
    // interface SearchType{ 
    //     title: string | null, 
    //     state?: {}|null|undefined, 
    //     creat: string | null | undefined ,
    //     num:number|null|undefined,
    //     size:number| null |undefined
    // }
    interface SearchType{ 
        title: string , 
        state?: {}, 
        creat: string  ,
        num:number,
        size:number
    }
    // const [searchList, setSearchList] = useState<SearchType>({
    //     title: null,
    //     state: null,
    //     creat: null,
    //     num : null,//页码
    //     size : null,//页码条数
    // })
    //表格方法
    const [searchList, setSearchList] = useState<SearchType>()
    //表格方法
    const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
    //switch 的布尔值判断
    const [switch1, setSwitch1] = useState<boolean[]>([])
    //路由跳转
    const navigate = useNavigate()
    //编辑表格的显示布尔值
    const [isModalOpen, setIsModalOpen] = useState(false);
    //编辑详情存储
    const [edit, setEdit] = useState<DataType>()
    //当前页码
    const [nowPage, setNowPage] = useState<number>(1)
    //总条数
    const [totalPage,setTotalPage] = useState<number>(5)
    const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
        //switch勾选的内容
        console.log('selectedRowKeys changed switch勾选的内容: ', newSelectedRowKeys);
        console.log('React', data);
        setSelectedRowKeys(newSelectedRowKeys);
    };
    useEffect(()=>{
        getvalue()
    },[nowPage,totalPage])
    //获取当页总数据
    const getvalue=()=>{
        getAllPromotion({num:nowPage,size:totalPage}).then(res=>{
            console.log('数据获取成功',res.data);
            if(res.code=='200'){
                let data = res.data.all
                setData(data)
                setCount(res.data.total)
                deTypeApi().then(res=>{
                    console.log('行程总数据',res);
                    setTypes(res.data)
                })
            }
        }).catch(err=>{
            console.log('获取数据失败',err); 
        })
    }
    
    const rowSelection = {
        // selectedRowKeys,
        onChange: onSelectChange,
    };
    // const hasSelected = selectedRowKeys.length > 0;
    //选项框的值
    const { Option } = Select;
    //onGenderChang选项框事件
    const onGenderChange = (value: string | number) => {
        console.log('onGenderChange===>',value);
        let newList = switchList.filter(item => item.choose == value)
        //筛选出来的对象
        console.log(newList[0]);
        let obj = newList[0]
        setState(obj)
        console.log('state', state);
    };
    //input 输入框的值
    const onInputChange = (e: any) => {
        // console.log('input的值',e.target.value);
        let name = e.target.value
        setTitle(name)
        console.log('name', name);
    }
    //日期选择
    const onChangeDate = (date:any,dateString:string) => {
        // console.log(dateString);
        setCreat(dateString)
        console.log('data', date);
    };
    //switch的change方法
    const onChange = (checked: boolean) => {
        // checked ? checked=true:checked=false
        console.log(`switch to ${checked}`);
    };
    //更改上架状态
    const switchClick = async (v:DataType) => {
        console.log(`switchClick事件获取到的`, v);
        let id = {id:v.id}
        let res = await changePromotionState({
            id:v.id
        })
        console.log("res",res);
        
    }
    //点击进入商品管理
    const commodityBtn = (v:any) => {
        console.log('commodityBtn事件获取到的', v);
        navigate('/home/promotion/commodity',{state:v})
    }
    //点击编辑
    const redactBtn = (v: DataType) => {
        console.log('点击编辑事件触发的', v)
        //编辑弹框点击弹出
        setEdit(v)
        setIsModalOpen(true)
    }
    //关闭弹框方法
    const closeCom = () => {
        setIsModalOpen(false)
    }
    //点击删除
    // const del = (v: any) => {
    //     console.log('删除的点击事件触发', v);
    //     showPromiseConfirm()
    // }
    //当前页码和页数
    const changePage=(page: number, pageSize: number):void=>{
        console.log('页码变了了', page, pageSize);
        setNowPage(page),
        setTotalPage(pageSize)
    }
    //声明周期里进行存储
    useEffect(()=>{
        setSearchList({
            title: title,
            state: state?.state,
            creat: creat,
            num : nowPage,//页码
            size : totalPage,//页码条数
        })
    },[title,state,creat])
    //点击筛选(查询)
    const filtrateBtn = () => {
        setSearchList({
            title: title,
            state: state?.state,
            creat: creat,
            num : nowPage,//页码
            size : totalPage,//页码条数
        })
        console.log('搜索的内容', searchList);
        getAllPromotion(searchList).then(res=>{
            console.log('查询陈宫',res);
            if(res.code=='200'){
                setData(res.data.all)
            }
        }).catch(err=>{
            console.log('查询失败',err);
            
        })
    }
    //重置按钮
    const rest = () => {
        console.log(searchList);
        getvalue()
    }
    //跳入添加促销页面
    const goAddBtn = () => {
        navigate('/home/promotion/addpromotion',{ state: types })
    }

    return (
        <div className='Promotionma'>
            {/* 头部 */}
            <div className='page-top'>
                <div className='page-title'>
                    <p>促销管理</p>
                </div>
            </div>

            {/* 内容框 */}
            <div className='page-content'>
                {/* 查询部分 */}
                <div className='filtrate-search'>
                    <p className='title'>筛选查询</p>
                    <div className='inputBox'>
                        <div>
                            <p>关键词：</p>
                            <Input
                                placeholder="输入关键词"
                                onChange={onInputChange}
                            />
                        </div>
                        <div>
                            <p>状态：</p>
                            <Select
                                placeholder="请选择状态"
                                onChange={onGenderChange}
                                allowClear
                            >
                                {switchList.map(item => {
                                    return <Option key={item.state} value={item.choose}>{item.choose}</Option>
                                })}
                            </Select>
                        </div>
                        <div>
                            <p>添加时间：</p>
                            {/* <DatePicker onChange={onChangeDate} className='dataList' /> */}
                            <DatePicker onChange={onChangeDate} className='dataList' renderExtraFooter={() => 'extra footer'} showTime />
                        </div>
                    </div>
                    <div className='buttonType'>
                        <button className='reset' onClick={rest}>重置</button>
                        <button className='filter' onClick={filtrateBtn}>筛选</button>
                    </div>
                </div>
                {/* 数据表格部分 */}
                <div className='data-list'>
                    <div className='headChoose'>
                        {/* 标题 */}
                        <p>数据列表</p>
                        <div>
                            {/* 排序方式 */}
                            <p style={{marginRight:"10px"}}>排序方式:</p>
                            <Select
                            style={{ width: 120 }}
                            options={sortName}
                            />
                            {/* 批量操作 */}
                            <button className='delBtn' style={{margin:"0 10px"}}>批量删除</button>
                            {/* 添加按钮 */}
                            <button className='add' onClick={goAddBtn}>添加促销</button>
                        </div>
                    </div>
                    <div className='contentType'>
                        <div style={{ marginBottom: 16 }}>
                        </div>
                        <ConfigProvider locale={zh_CN}>
                            <Table rowSelection={rowSelection}
                                columns={columns}
                                dataSource={data}
                                scroll={{ y: 444 }}
                                rowKey={item=>item.id}
                                pagination={{
                                    position: ['bottomCenter'],
                                    defaultPageSize: 3,
                                    pageSizeOptions: [3, 5, 10, 15],
                                    showQuickJumper: true,
                                    showSizeChanger: true,
                                    total:count,
                                    onChange: changePage
                                }} />
                            {/* 编辑弹框 */}
                            <Compile isModalOpen={isModalOpen} closeCom={closeCom} edit={edit}></Compile>
                        </ConfigProvider>
                    </div>
                </div>
            </div>
        </div>
    )
}

export default Promotionma
// 促销管理